<template>
  <div class="page-main" v-title data-title="配料信息库">
    <home-nav :userData="userinfo"></home-nav>
    <div class="banner"><span>配料信息库</span></div>
    <div class="container">
      <div class="container-bg">
        <div class="header">
          <a-row type="flex" justify="space-between" align="middle">
            <a-col :xl="{ span: 11 }" :lg="{ span: 11 }">
              <a-button class="hte-btn add-btn" type="primary" icon="plus" @click="handAction('add')">新增</a-button>
              <a-button class="hte-btn" @click="handAction('upd')">修改</a-button>
              <a-button class="hte-btn" @click="excelVisible=true">导入</a-button>
              <a-button class="hte-btn" @click="handlePostExportXls('配料信息库')">导出</a-button>
              <a-button class="hte-btn" type="danger" @click="handAction('del')">删除</a-button>
              <a-button class="hte-btn" @click="refresh">刷新</a-button>
            </a-col>
            <a-col :xl="{ span: 9 }" :lg="{ span: 13 }" class="input-ground">
              <a-input-group compact>
                <a-select v-model="searchField" @change="changeKeywordType">
                  <a-select-option value="materialNoStr"> 物料编号 </a-select-option>
                  <a-select-option value="materialName"> 物料名称 </a-select-option>
                </a-select>
                <a-input-search
                  v-if="searchField == 'materialNoStr'"
                  v-model="queryParam.materialNoStr"
                  @search="doSearch"
                  allowClear
                  placeholder="请输入关键词检索"
                />
                <a-input-search
                  v-if="searchField == 'materialName'"
                  v-model="queryParam.materialName"
                  @search="doSearch"
                  allowClear
                  placeholder="请输入关键词检索"
                />
              </a-input-group>
              <a-button class="hte-btn del-btn" @click="visibleModel = true">高级查询</a-button>
            </a-col>
          </a-row>
        </div>
        <div class="content">
          <a-table
            class="hte-table-content"
            :scroll="{ x: 1500 }"
            :columns="columns"
            :data-source="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            rowKey="id"
            size="middle"
            @change="handleTableChange"
          >
            <template slot="swicth" slot-scope="text">
              <span>{{ text ? '是' : '否' }}</span>
            </template>
            <template slot="materialNo" slot-scope="text, record">
              <span class="clickspan" @click="handAction('upd', record)">{{ text }}</span>
            </template>
          </a-table>
        </div>
      </div>
    </div>
    <a-back-top class="backtodom" />
    <!-- 高级查询 -->
    <advanced-search
      :dataForm.sync="queryParam"
      :visible="visibleModel"
      ref="advanced"
      :formCol="queryParamCol"
      @ok="callBackResult"
      @reset="resetResulte"
      @close="closeResulte"
    >
    </advanced-search>
    <!-- 新增/修改 -->
    <BurdenAddModal ref="burdenAdd" :washType="washType" @ok="doSearch"></BurdenAddModal>
    <!-- 导入 -->
    <excel-paste
      :columnsExcel="columnsExcel"
      :exportXlsTemplateUrl="exportXlsTemplateUrl"
      :excelVisible="excelVisible"
      :excelConfirmLoading="excelConfirmLoading"
      @handleOkExcel="handleOkExcel"
      @handleCancelExcel="handleCancelExcel"
    ></excel-paste>
  </div>
</template>
<script>
import Vue from 'vue'
import { getAction, postAction,downloadFileLink} from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListSearchMixin'
import { USER_INFO } from '@/store/mutation-types'
import ExcelPaste from '@/components/excelPaste/ExcelPaste'
import { ClearLibMixin } from '@/mixins/ClearLibMixin'
import {codeInfoList} from '@/api/codeInfo'
export default {
  name: 'BurdenList',
  mixins: [JeecgListMixin,ClearLibMixin],
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    AdvancedSearch: () => import('@/components/tools/AdvancedSearch'),
    BurdenAddModal: () => import('./burdenAddModal'),
    ExcelPaste
  },
  data() {
    return {
      disableMixinCreated:true,
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'BurdenList',
      },
      currUser: Vue.ls.get(USER_INFO).username,
      columns: [
        {
          title: '配料编号',
          dataIndex: 'materialNoStr',
          width: 120,
          align: 'center',
          scopedSlots: { customRender: 'materialNo' },
        },
        { title: '配料名称', dataIndex: 'materialName', width: 180, align: 'center' },
        { title: '过敏原', dataIndex: 'allergy', width: 120, align: 'center', scopedSlots: { customRender: 'swicth' }, },
        { title: '特殊属性', dataIndex: 'specialAttributesName', width: 120, align: 'center'},
        { title: '配料分组', dataIndex: 'materialGroupName', width: 120, align: 'center', },
        { title: '创建人', dataIndex: 'createUserName', width: 120, align: 'center' },
        { title: '创建时间', dataIndex: 'createTime', width: 180, align: 'center' },
        { title: '备注', dataIndex: 'remark', width: 200, align: 'center', ellipsis: true },
      ],
      url: {
        list: '/hteWashMaterial/page', // 搜索
        delBatch: '/hteWashMaterial/delBatch', // 删除
        exportXlsUrl: '/hteWashMaterial/export', // 导出
        addBatch: '/hteWashMaterial/addBatch', // 导入
      },
      // 高级查询
      visibleModel: false,
      searchField: 'materialNoStr',
      queryParam: {
        materialNoStr: '',
        materialName: '',
      },
      queryParamCol: [
        { type: 'input', model: 'materialNoStr', label: '配料编号' },
        { type: 'input', model: 'materialName', label: '配料名称' },
      ],
      // 导入
      exportXlsTemplateUrl: 'templates/excel/washMaterialTemplate.xlsx', //导入模板
      excelVisible: false,
      excelConfirmLoading: false,
      columnsExcel: [],
      dict:{},
    }
  },
  created(){
     this.loadData(1);
  },
  mounted() {
    this.initDics()
    this.columnsExcel = this.columns.filter(item=>{
      return ['配料名称', '过敏原','特殊属性', '配料分组', '备注'].includes(item.title)
    })
  },
  methods: {
    refresh() {
      this.loadData()
    },
    doSearch() {
      this.loadData(1)
    },
    changeKeywordType() {
      if (this.searchField == 'materialNoStr') {
        this.$set(this.queryParam, 'materialName', '')
      } else {
        this.$set(this.queryParam, 'materialNoStr', '')
      }
    },
    /**
     * 高级搜索
     */
    callBackResult() {
      this.visibleModel = false
      this.doSearch()
    },
    closeResulte() {
      this.visibleModel = false
    },
    resetResulte() {
      this.queryParam = {}
    },
    initDics(){
      const list = [{name:'materialGroup',type:`${this.washType}配料分组`},{name:'specialAttributes',type:`${this.washType}特殊属性`} ]
      list.forEach((item, index)=>{
        codeInfoList({type:item.type,pageSize:-1,isdel: 0,column:"code",order:"Asc"}).then((res) => {
          if (res.code == 200) {
            this.dict[item.name] = res.result.records
           
          } else {
            this.$message.warning('操作异常:' + res.message)
          }
        })
      })      
    },
    /**
     * 操作
     */
    handAction(type, id) {
      switch (type) {
        case 'add':
          // 新增
          this.$refs.burdenAdd.dict = Object.assign(this.$refs.burdenAdd.dict,this.dict)
          this.$refs.burdenAdd.showVisible()
          break
        case 'del':
          // 删除，可多选
          const that = this
          if (this.selectedRowKeys.length == 0) {
            this.$message.warning('请选择至少一条数据！')
            return
          }
          this.$confirm({
            title: '确认删除',
            content: '请确认是否删除此信息?',
            onOk: function () {
              postAction(that.url.delBatch, that.selectedRowKeys).then((res) => {
                if (res.code == 200) {
                  that.$message.success('删除成功')
                  that.loadData();
                } else {
                  that.$message.warning('删除失败:' + res.message)
                }
              })
            },
          })
          break
        case 'upd':
          // 修改
          if (!id && this.selectedRowKeys.length != 1) {
            this.$message.warning('请选择一条数据！')
            return
          }
          this.$refs.burdenAdd.dict = Object.assign(this.$refs.burdenAdd.dict,this.dict)
          this.$refs.burdenAdd.showVisible(id || this.selectionRows[0])
          break
        default:
          break
      }
    },
    /**
     * 导入 
     */
    handleCancelExcel: function () {
      this.excelVisible = false
    },
    handleOkExcel: function (data) {
      debugger
      let flag = false
      for (let index = 0; index < data.length; index++) {
        const element = data[index]; 
        element.washType = this.washType
        for (let item of Object.keys(element)){
          if(item!='key' && item!='remark' && item!='specialAttributesName' && item!='materialGroupName'  &&!element[item] ) {
            flag = true
            this.$message.warning('第 '+(index+1)+' 行，请先把信息填写完整');
            break
          }
          if(item == 'allergy'){
            if(element[item]=='是'){
              element[item] = true;
            
            }else{
              element[item] = false;
            }
          }
         
          if(item == 'specialAttributesName'){
            if(element[item] ){
              let findDict = this.dict.specialAttributes.find(spe=>{return spe.name == element[item]})
             
              if(!findDict){
                flag = true
                this.$message.warning(`第 '+(index+1)+' 行，特殊属性【${element[item]}】不存在`);
                break
              }
              element.specialAttributes = findDict.code
            }
          }
           if(item == 'materialGroupName'){
            if(element[item] ){
              let findDict = this.dict.materialGroup.find(spe=>{return spe.name == element[item]})
             
              if(!findDict){
                flag = true
                this.$message.warning(`第 '+(index+1)+' 行，配料分组【${element[item]}】不存在`);
                break
              }
              element.materialGroup = findDict.code
            }
          }
        }
        if(flag){
          return
        }
      }      
      this.excelConfirmLoading = true
      postAction(this.url.addBatch, data)
        .then((res) => {
          this.excelConfirmLoading = false
          if (res.code === 200) {
            this.excelVisible = false
            this.$message.success('导入成功')
            this.loadData()
          } else {
            this.$message.warning(res.message)
          }
        })
        .catch((res) => {
          this.excelConfirmLoading = false
          this.$message.warning('操作异常:' + res.message)
        })
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
@import '~@views/library/clearSoln/index.less';
</style>
